package com.woniuxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.*;
import com.woniuxy.entity.dto.NormalOrderDTO;
import com.woniuxy.entity.dto.NormalOrderDTO2;
import com.woniuxy.entity.dto.VehicleModelDTO;
import com.woniuxy.entity.dto.WaybillDTO;
import com.woniuxy.mapper.TransportMapper;
import com.woniuxy.mapper.WaybillMapper;
import com.woniuxy.service.WaybillService;
import com.woniuxy.util.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WaybillServiceImpl implements WaybillService {
    @Resource
    private WaybillMapper waybillMapper;
    @Resource
    private TransportMapper transportMapper;

    @Resource
    private ExportService exportService;
    @Override
    public ResponseData<?> queryWaybill(PageData<WaybillDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(),pageData.getPageSize());
        List<WaybillDTO> waybills = waybillMapper.queryWaybill(pageData.getParam());
        PageInfo pageInfo = new PageInfo(waybills);
        return new ResponseData<>().ok(pageInfo);
    }

    /**
     * 查询运输方式
     */
    @Override
    public ResponseData<?> queryTransport() {
        List<Transport> transports = transportMapper.queryTransport();
        return new ResponseData<>().ok(transports);
    }

    @Override
    public ResponseData<?> queryBasicDetail(String id) {
        WaybillDTO waybillDTO = waybillMapper.queryBasicDetail(id);
        return new ResponseData<>().ok(waybillDTO);
    }
    @Override
    public ResponseData<?> querySendDetail(String id) {
        WaybillDTO waybillDTO = waybillMapper.querySendDetail(id);
        return  new ResponseData<>().ok(waybillDTO);
    }

    @Override
    public ResponseData<?> queryGoodsDetail(String id) {
        List<NormalOrderDTO2> normalOrderDTOS = waybillMapper.queryGoodsDetail(id);
        return new ResponseData<>().ok(normalOrderDTOS);
    }

    @Override
    public ResponseData<?> queryAllLogisticsPartner() {
        List<LogisticsPartner> logisticsPartners = waybillMapper.queryAllLogisticsPartner();
        return new ResponseData<>().ok(logisticsPartners);
    }

    @Override
    public ResponseData<?> queryDriver() {
        List<DriverManagement> driverManagements = waybillMapper.queryDriver();
        List<DriverManagement> driverManagements1 = new ArrayList<>();
        for (DriverManagement driverManagement : driverManagements) {

            // 获取当前时间
            LocalDateTime currentTime = LocalDateTime.now();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化当前时间为字符串
            String formattedDateTime = currentTime.format(formatter);  //当前时间字符串

            String licenseExpiration = driverManagement.getLicenseExpiration(); //有效日期字符串

            // 解析字符串为LocalDate对象
            LocalDate nowTime = LocalDate.parse(formattedDateTime, formatter);

            LocalDate validTime = LocalDate.parse(licenseExpiration, formatter); //有效日期
            // 比对nowTime和validTime两个时间的大小
            if (nowTime.isBefore(validTime)) {
                driverManagements1.add(driverManagement);
            }

        }
        return new ResponseData<>().ok(driverManagements1);
    }

    @Override
    public ResponseData<?> queryById(String id) {
        LogisticsPartner logisticsPartner = waybillMapper.queryById(id);
        return new ResponseData<>().ok(logisticsPartner);
    }

    @Override
    public ResponseData<?> queryDriverById(String id) {
        DriverManagement driverManagement = waybillMapper.queryDriverById(id);
        return new ResponseData<>().ok(driverManagement);
    }

    @Override
    public ResponseData<?> queryCar(String id) {
        List<Vehicle> vehicles = waybillMapper.queryCar(id);
        return new ResponseData<>().ok(vehicles);
    }

    @Override
    public ResponseData<?> queryCarById(String id) {
        VehicleModel vehicleModel = waybillMapper.queryCarById(id);
        return new ResponseData<>().ok(vehicleModel);
    }

    @Override
    public ResponseData<?> queryDispatch(String id) {
        LogisticsPartner logisticsPartner = waybillMapper.queryDispatch(id);
        return new ResponseData<>().ok(logisticsPartner);
    }

    @Override
    public ResponseData<?> queryD(String id) {
        DriverManagement driverManagement = waybillMapper.queryD(id);
        return new ResponseData<>().ok(driverManagement);
    }

    @Override
    public ResponseData<?> queryC(String id) {
        VehicleModelDTO VehicleModelDTO = waybillMapper.queryC(id);
        return new ResponseData<>().ok(VehicleModelDTO);
    }

    @Override
    public ResponseData<?> queryDate(String id) {
        Waybill waybill = waybillMapper.queryDate(id);
        return new ResponseData<>().ok(waybill);
    }

    @Override
    public ResponseData<?> judgment(String id) {  //承运商跳转判断
        Waybill waybill = waybillMapper.queryWaybillStatus(id);
        String status = waybill.getStatus();
        if ("1".equals(status) || "2".equals(status)){
            return new ResponseData<>().ok();
        }
        //返回2015代表无法点分配
        return new ResponseData<>().fail(ResponseEnum.ORDER_ERROR);
    }

    @Override
    public ResponseData<?> save(WaybillDTO waybillDTO) {
        //根据运单号查询 查询订单表货物体积和重量
        //根据车牌id查询车辆信息，体积和承重
        //判断，体积或承重不满足，返回code码2001
        String waybillDTOId = waybillDTO.getId();
        String carrierId = waybillDTO.getCarrierId();
        String carId1 = waybillDTO.getCarId();
        String driverId = waybillDTO.getDriverId();
        if(carrierId==null|| carId1==null || driverId==null){
            return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR2);
        }else{
        NormalOrder normalOrder = waybillMapper.queryNormalOrder(waybillDTOId);  //货物信息
        String allVolume = normalOrder.getAllVolume();
        String allWeight = normalOrder.getAllWeight();

        String carId = waybillDTO.getCarId();  //得到车牌号对应id
        VehicleModel vehicleModel = waybillMapper.queryVehicleModel(carId); // 车辆承重信息
        String loadVolume = vehicleModel.getLoadVolume();
        String loadWeight = vehicleModel.getLoadWeight();
        //货物重量和体积同时小于或等于车辆承载值，进行分配承运商操作，否则返回code码值
//        allVolume.compareTo(loadVolume) <= 0 && allWeight.compareTo(loadWeight) <= 0
        if((Integer.parseInt(allVolume)-Integer.parseInt(loadVolume))<0 && (Integer.parseInt(allWeight)-Integer.parseInt(loadWeight))<0){
            //分配承运商，司机，车辆 ，两个计划时间 ,
            Waybill waybill = new Waybill();
            waybill.setId(waybillDTOId);
            waybill.setLogisticsPartnerId(waybillDTO.getCarrierId());
            waybill.setDriverManagementId(waybillDTO.getDriverId());
            waybill.setVehicleId(carId);
            waybill.setPlanArrivalTime(waybillDTO.getPlanArrivalTime());
            waybill.setPlanDepartureTime( waybillDTO.getPlanDepartureTime());
            Long userId = UserContext.getUserId();
            waybill.setFinalPoweruserId(String.valueOf(userId.intValue()));

            Vehicle vehicle = waybillMapper.queryVehicleById(carId);
            String vehicleModelId = vehicle.getVehicleModelId();
            waybill.setVehicleModelId(vehicleModelId);
            waybillMapper.updateWaybill(waybill);
            waybillMapper.updateNormalOrderStatus(waybillDTOId);//修改订单表状态为待提货
            Waybill waybill2 = waybillMapper.queryWaybillById(waybillDTOId);
            waybillMapper.updateDriverStatus(waybill2.getDriverManagementId());

            //生成提货单
            // 生成雪花id主键字段，运单号id，订单号id， customer_id 在订单表,
            SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
            String orderNum = String.valueOf(sg.nextId());
            String prefixedOrderNum = "T" + orderNum;  //运单的雪花ID
            PickupOrder pickupOrder = new PickupOrder();
            pickupOrder.setId(prefixedOrderNum);
            pickupOrder.setWaybillId(waybillDTOId);
            pickupOrder.setOrderId(normalOrder.getId());
            pickupOrder.setCustomerId(normalOrder.getCustomerId());
            pickupOrder.setDeliveryAddressId(normalOrder.getDeliveryAddressId());
            pickupOrder.setPickupAddressId(normalOrder.getPickupAddressId());
            Waybill waybill1 = waybillMapper.queryWaybillById(waybillDTOId);
            pickupOrder.setDriverId(Integer.valueOf(waybill1.getDriverManagementId()));
            pickupOrder.setVehicleId(Integer.valueOf(waybill1.getVehicleId()));
            waybillMapper.addPickupOrder(pickupOrder);
            return  new ResponseData<>().ok();

        }else{
            //否则返回code码值 2009 车辆超载
            return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR1);
        }

        }
    }


    @Override
    public ResponseData<?> Cancel(String id) {
        Waybill waybill = waybillMapper.queryWaybillStatus(id);
        String status = waybill.getStatus();
        if("1".equals(status)){
            //没绑定
            return new ResponseData<>().fail(ResponseEnum.SYS_BUSY);
        }else if ("2".equals(status)) {
            //执行解绑操作
            Long userId = UserContext.getUserId();
            Waybill waybill2 = new Waybill();
            waybill2.setId(id);
            waybill2.setFinalPoweruserId(String.valueOf(userId.intValue()));
            //修改司机状态
            Waybill waybill1 = waybillMapper.queryWaybillById(id);
            waybillMapper.updateDriverStatus1(waybill1.getDriverManagementId());

            waybillMapper.CancelupdateWaybill(waybill2);
            //修改订单表状态为0
            NormalOrder normalOrder = waybillMapper.queryNormalOrderById(id);
            String normalOrderId = normalOrder.getId();
            waybillMapper.updateNormalOrderStatus2(normalOrderId);
            //删除提货单表id
            waybillMapper.deletePickupOrderId(id);

            return  new ResponseData<>().ok();
            }
            //不能被解绑，返回code码值 2001
        return new ResponseData<>().fail(ResponseEnum.LOGIN_ERROR);

    }


    @Override
    public ResponseData<?> batchDel(List<String> ids) {
        for (String id : ids) {
            Waybill waybill = waybillMapper.queryWaybillStatus(id);
            String status = waybill.getStatus();
            if(!("2".equals(status))){
                //不能批量操作
                return new ResponseData<>().fail(ResponseEnum.LOGIN_ERROR);
            }
        }
        //执行解绑操作
        Long userId = UserContext.getUserId();
        waybillMapper.batchDel(ids, String.valueOf(userId));
        //批量修改订单状态为0
        waybillMapper.batchUpdateNormalOrderStatus2(ids);
        //批量删除提货单id
        waybillMapper.batchDeletePickupOrderId(ids);
        return  new ResponseData<>().ok();
    }


    /**
     * 导出功能
     * @param response
     * @return
     */
    @SneakyThrows
    @Override
    public ResponseData<?> exportYiData(HttpServletResponse response) {
        List<Map<String, Object>> yiData = waybillMapper.queryException2(null);

        // 字段名与中文表头的映射关系
        Map<String, String> fieldToChineseMap = new HashMap<>();


        exportService.exportDynamicDataToExcel(response, yiData, fieldToChineseMap);

        return new ResponseData<>().ok();
    }
}
